<template>
    <el-card>
        <el-form inline class="flex">
            <el-form-item label="用户名">
                <el-input
                    placeholder="请输入用户名"
                    style="width: 200px"
                    v-model="keyword"
                ></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :disabled="!keyword" @click="search">
                    搜索
                </el-button>
                <el-button @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card class="base-margin">
        <el-form>
            <el-form-item>
                <el-button type="primary" @click="addUser">添加用户</el-button>
                <el-button
                    type="danger"
                    @click="deleteUserList"
                    :disabled="!selectUserList.length"
                >
                    批量删除
                </el-button>
            </el-form-item>
            <el-form-item>
                <el-table border :data="userList" @select="selectUser">
                    <el-table-column
                        type="selection"
                        width="50"
                        align="center"
                    ></el-table-column>
                    <el-table-column
                        label="#"
                        type="index"
                        width="50"
                        align="center"
                    ></el-table-column>
                    <el-table-column
                        label="ID"
                        align="center"
                        prop="id"
                    ></el-table-column>
                    <el-table-column
                        label="用户名字"
                        show-overflow-tooltip
                        align="center"
                        prop="username"
                    ></el-table-column>
                    <el-table-column
                        label="用户名称"
                        show-overflow-tooltip
                        align="center"
                        prop="name"
                    ></el-table-column>
                    <el-table-column
                        label="用户角色"
                        show-overflow-tooltip
                        align="center"
                        prop="roleName"
                    ></el-table-column>
                    <el-table-column
                        label="创建时间"
                        show-overflow-tooltip
                        align="center"
                        prop="createTime"
                    ></el-table-column>
                    <el-table-column
                        label="更新时间"
                        show-overflow-tooltip
                        align="center"
                        prop="updateTime"
                    ></el-table-column>
                    <el-table-column label="操作" align="center" width="350">
                        <template #="{ row }">
                            <el-button
                                type="primary"
                                icon="User"
                                size="small"
                                @click="Distribution(row)"
                            >
                                分配角色
                            </el-button>
                            <el-button
                                type="primary"
                                icon="Edit"
                                size="small"
                                @click="updateUser(row)"
                            >
                                编辑
                            </el-button>

                            <el-popconfirm
                                title="Are you sure to delete this?"
                                @confirm="deleteUser(row.id)"
                            >
                                <template #reference>
                                    <el-button
                                        type="primary"
                                        icon="Delete"
                                        size="small"
                                    >
                                        删除
                                    </el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
        </el-form>
        <el-pagination
            @change="getUserList"
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 7, 9, 11]"
            background
            layout=" prev, pager, next, jumper,->,total, sizes"
            :total="total"
            class="base-margin"
        />

        <el-dialog
            :title="userParams.id ? '编辑用户' : '添加用户'"
            v-model="dialogTableVisible"
        >
            <el-form
                label-width="100"
                :model="userParams"
                :rules="rules"
                ref="formRef"
            >
                <el-form-item label="用户名" prop="username">
                    <el-input
                        placeholder="请输入用户名"
                        style="width: 200px"
                        v-model="userParams.username"
                    ></el-input>
                </el-form-item>
                <el-form-item label="用户名称" prop="name">
                    <el-input
                        v-model="userParams.name"
                        placeholder="请输入用户名称"
                        style="width: 200px"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="用户密码"
                    v-show="!userParams.id"
                    prop="password"
                >
                    <el-input
                        v-model="userParams.password"
                        placeholder="请输入密码"
                        type="password"
                        style="width: 200px"
                    ></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="save">确定</el-button>
                    <el-button @click="cancel">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <el-drawer v-model="drawer">
            <template #header>
                <span>分配角色</span>
            </template>
            <template #default>
                <el-form>
                    <el-form-item label="用户姓名">
                        <el-input
                            v-model="userParams.username"
                            :disabled="true"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="角色列表">
                        <el-checkbox
                            v-model="checkAll"
                            :indeterminate="isIndeterminate"
                            @change="handleCheckAllChange"
                        >
                            全选
                        </el-checkbox>
                        <el-checkbox-group
                            v-model="checked"
                            @change="handleCheckedCitiesChange"
                        >
                            <el-checkbox
                                v-for="item in allRole"
                                :key="item.id"
                                :label="item"
                                :value="item"
                                @change="getRoleID(item)"
                            >
                                {{ item.roleName }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
            </template>
            <template #footer>
                <el-button type="primary" @click="drawer = false">
                    取消
                </el-button>
                <el-button type="primary" @click="doAssignRole">保存</el-button>
            </template>
        </el-drawer>
    </el-card>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue';
import { useSettingStore } from '@/store/modules/setting';
import {
    reqGetUserList,
    reqAddOrUpdateUser,
    reqGetAllRole,
    reqAssignRole,
    reqDeleteUser,
    reqUserList,
} from '@/api/acl/user/index';
import type {
    UserResponse,
    Records,
    Roles,
    AllRolesData,
    AssignRoleData,
} from '@/api/acl/user/type';
import { ElMessage } from 'element-plus';
const currentPage = ref(1); // 当前页数
const pageSize = ref(5); // 每页显示的条数
const total = ref(100); // 总条数
const userList = ref<Records[]>();
const dialogTableVisible = ref<boolean>(false);
const drawer = ref<boolean>(false);
// 是否全选
const checkAll = ref(false);
const isIndeterminate = ref(true);
const checked = ref();
const allRole = ref<Roles[]>([]);
const formRef = ref();
// 收集参数
let userParams = reactive<Records>({
    username: '',
    name: '',
    password: '',
});
let AssignParams = reactive<AssignRoleData>({
    userId: '',
    roleIdList: [],
});
const settingStore = useSettingStore();
// 搜索需要的响应式数据
const keyword = ref<string>('');
onMounted(() => {
    getUserList();
});

const getUserList = async () => {
    const res: UserResponse = await reqGetUserList(
        currentPage.value,
        pageSize.value,
        keyword.value,
    );

    if (res.code === 200) {
        userList.value = res.data.records;
        currentPage.value = res.data.current;
        pageSize.value = res.data.size;
        total.value = res.data.total;
    }
};
// 添加用户
const addUser = () => {
    dialogTableVisible.value = true;
    init();
    nextTick(() => {
        formRef.value.clearValidate('username');
        formRef.value.clearValidate('name');
    });
};
// 编辑用户
const updateUser = async (row: Records) => {
    // 记录坑 不能这么赋值，会破坏响应性
    // userParams = { ...row }
    userParams.id = row.id;
    userParams.username = row.username;
    userParams.name = row.name;
    userParams.password = row.password;
    dialogTableVisible.value = true;
    nextTick(() => {
        formRef.value.clearValidate('username');
        formRef.value.clearValidate('name');
        formRef.value.clearValidate('password');
    });
};
// 清空表单数据
const init = () => {
    Object.assign(userParams, {
        username: '',
        name: '',
        password: '',
        id: '',
    });
};
// 保存用户
const save = async () => {
    const res = await reqAddOrUpdateUser(userParams);
    if (res.code === 200) {
        dialogTableVisible.value = false;
        ElMessage.success('成功');
        init();
        window.location.reload();
    }
};
// 修改
const cancel = async () => {
    dialogTableVisible.value = false;
    init();
};
// 分配角色
const Distribution = async (row: Records) => {
    userParams = { ...row };
    drawer.value = true;
    const res: AllRolesData = await reqGetAllRole(row.id as number);
    if (res.code === 200) {
        allRole.value = res.data.allRolesList;
        checked.value = res.data.assignRoles;
    }
};
const handleCheckAllChange = (val: any) => {
    checked.value = val ? allRole.value : [];
    isIndeterminate.value = false;
};
const handleCheckedCitiesChange = (value: any) => {
    const checkedCount = value.length;
    checkAll.value = checkedCount === allRole.value.length;
    isIndeterminate.value =
        checkedCount > 0 && checkedCount < allRole.value.length;
};

// 分配角色
const getRoleID = async (item: any) => {
    AssignParams.userId = userParams.id as string;
    AssignParams.roleIdList = checked.value.map((item: any) => item.id);
};
const doAssignRole = async () => {
    const res: any = await reqAssignRole(AssignParams);
    if (res.code === 200) {
        drawer.value = false;
        getUserList();
    }
};

// 删除某一用户
const deleteUser = async (id: number) => {
    const res = await reqDeleteUser(id);
    if (res.code === 200) {
        ElMessage.success('删除成功');
        getUserList();
    } else {
        ElMessage.error('删除失败');
    }
};
// 删除多个用户
const selectUserList = ref<Records[]>([]);
const selectUser = (selection: Records[]) => {
    selectUserList.value = selection;
};
const deleteUserList = async () => {
    const idList: any = selectUserList.value.map((item: Records) => item.id);
    const res: any = await reqUserList(idList);
    if (res.code === 200) {
        ElMessage.success('批量删除成功');
        getUserList();
    } else {
        ElMessage.error('批量删除失败');
    }
};
const search = () => {
    getUserList();
};
const reset = () => {
    settingStore.refresh = true;
};
// 自定义校验规则
const validatrUserName = (rule: any, value: any, callback: any) => {
    console.log('value', value);
    if (value.trim().length < 5) {
        callback(new Error('用户名不能小于5位'));
    }
    callback();
};
const validatrName = (rule: any, value: any, callback: any) => {
    const regex = /^[a-zA-Z0-9]{5,10}$/;
    if (!regex.test(value)) {
        callback(new Error('用户名称不能小于5位'));
    }
    callback();
};
const validatrPass = (rule: any, value: any, callback: any) => {
    const regex = /^[a-zA-Z0-9]{6,10}$/;
    if (!regex.test(value)) {
        callback(new Error('密码不能小于6位'));
    }
    callback();
};
// 表单检验
const rules = reactive({
    username: [
        { required: true, validator: validatrUserName, trigger: 'blur' },
    ],
    name: [{ required: true, validator: validatrName, trigger: 'blur' }],
    password: [{ required: true, validator: validatrPass, trigger: 'blur' }],
});
</script>

<style scoped>
.flex {
    display: flex;
    justify-content: space-between;
}
</style>
@/api/acl/user/index@/api/acl/user/type
